part of base_package;

abstract class BasePageState<T extends BasePage> extends State<T> {
  StreamSubscription? _subscription;

  /// 屏幕宽度
  double widthScreen = 0;

  /// 屏幕高度
  double heightScreen = 0;

  /// 页面名称
  String pageName = T.toString();

  /// eventbus事件监听
  eventListen(Event event) {}

  /// eventbus事件发送
  eventFire(int type, {dynamic data = ""}) {
    Event.eventBus.fire(Event(type, data));
  }

  /// 初始化数据
  initData();

  /// 销毁数据
  destroyData();

  /// 加载框显示
  loadingShow({String? status}) {
    EasyLoading.show(status: status);
  }

  /// 加载框消失
  loadingDismiss() {
    EasyLoading.dismiss();
  }

  /// 设置页面内容
  Widget setPageContent(BuildContext context);

  /// 返回按钮事件处理
  Future<bool> backClick() {
    return Future.value(true);
  }

  /// 跳转界面 A->B
  Future<Map?> push(BuildContext context, BasePage page) async {
    return await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (_) {
          return page;
        },
      ),
    );
  }

  /// 跳转界面 A->B,A界面销毁
  pushReplacement(BuildContext context, BasePage page) {
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(
        builder: (_) {
          return page;
        },
      ),
    );
  }

  /// 销毁页面
  finishPop(BuildContext context, {Map? callBackData}) {
    Navigator.pop(context, callBackData);
  }

  @override
  void initState() {
    RouteList.list.add(T.toString());
    //订阅eventbus
    _subscription = Event.eventBus.on<Event>().listen((event) {
      eventListen(event);
    });
    BaseGlobal.currentPageName = pageName;
    initData();
    super.initState();
  }

  @override
  void dispose() {
    RouteList.list.remove(T.toString());
    _subscription?.cancel();
    loadingDismiss();
    destroyData();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    widthScreen = MediaQuery.of(context).size.width;
    heightScreen = MediaQuery.of(context).size.height;
    return WillPopScope(
      onWillPop: () => backClick(),
      child: setPageContent(context),
    );
  }

  /// 关闭键盘
  closeKeyboard() {
    FocusManager.instance.primaryFocus?.unfocus();
  }

  /// 获取热更新版本号
  Future<int> getHotJson(String appid) async {
    try {
      Response response = await Net.tempDio.request(
          'http://update.agent.xykjcloud.com/AndroidApp/$appid/hot.json');
      String jsonStr = json.encode(response.data);
      Map<String, dynamic> map = json.decode(jsonStr);
      return map['hotVersion'];
    } on Exception catch (e) {
      log('获取热更新json文件异常：${e.toString()}');
      return -1;
    }
  }
}
